package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"video/mysql/cache"
	"video/mysql/model"

	"video/videorpc/internal/svc"
	"video/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户注册
func (l *RegisterLogic) Register(in *videorpc.RegisterRequest) (*videorpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user model.User
	model.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID != 0 {
		return nil, errors.New("该手机号已注册,可直接登录")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.SendSms {
		return nil, errors.New("短信验证码错误,注册失败")
	}

	user = model.User{
		Account:   in.Account,
		Password:  in.Password,
		NickName:  fmt.Sprintf("游客_%d", rand.Intn(10000)),
		HeadImage: "https://ts1.tc.mm.bing.net/th/id/OIP-C.-rBqkricrrEXBZsFzjxtlQAAAA?cb=ucfimgc2&rs=1&pid=ImgDetMain&o=7&rm=3",
	}
	model.DB.Debug().Create(&user)

	return &videorpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
